package sdk.webview.fmc.com.fmcsdk.check;


import android.text.TextUtils;

import com.google.gson.Gson;
import com.tencent.mmkv.MMKV;


import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import sdk.webview.fmc.com.fmcsdk.bean.CaUploadImage;
import sdk.webview.fmc.com.fmcsdk.bean.GETREPORTBean;
import sdk.webview.fmc.com.fmcsdk.bean.StartPauseBean;
import sdk.webview.fmc.com.fmcsdk.bean.SubMitListBean;
import sdk.webview.fmc.com.fmcsdk.bean.SubMitPointBean;
import sdk.webview.fmc.com.fmcsdk.bean.UploadImageBean;
import sdk.webview.fmc.com.fmcsdk.check.bean.GetDetailsBean;
import sdk.webview.fmc.com.fmcsdk.check.bean.ImageFileBean;
import sdk.webview.fmc.com.fmcsdk.imagepicker.utils.Utils;
import sdk.webview.fmc.com.fmcsdk.service.UploadEventLoad;
import sdk.webview.fmc.com.fmcsdk.upload.ImageUploadBean;
import sdk.webview.fmc.com.fmcsdk.util.GsonUtil;
import sdk.webview.fmc.com.fmcsdk.util.KLog;

public class CacheHelper {
    private static CacheHelper cacheHelper;
    private MMKV userKv;

    private MMKV catchKv;

    private CacheHelper() {
        if (userKv == null) {
            StringBuilder stringBuilder = new StringBuilder(Utils.getContext().getFilesDir().getAbsolutePath())
                    .append("/mmkv");
            Utils.fileExits(stringBuilder.toString());
            MMKV.initialize(stringBuilder.toString());
        }
        userKv = MMKV.mmkvWithID("app");

        if (catchKv == null) {
            StringBuilder stringBuilder = new StringBuilder(Utils.getContext().getFilesDir().getAbsolutePath())
                    .append("/mmkv");
            Utils.fileExits(stringBuilder.toString());
            MMKV.initialize(stringBuilder.toString());
        }
        catchKv = MMKV.mmkvWithID("appPp");

    }

    public static CacheHelper getInstance() {
        if (cacheHelper == null) {
            synchronized (CacheHelper.class) {
                if (cacheHelper == null) {
                    cacheHelper = new CacheHelper();
                }
            }
        }
        return cacheHelper;
    }

    public String getActivityJson(String type) {
        return userKv.decodeString(type);
    }

    public void setActivityJson(String json, String type) {
        if (userKv == null) return;
        userKv.encode(type, json);
    }

    public List<ImageFileBean> getSaveImageFile(String idType) {
        List<ImageFileBean> list = new ArrayList<>();
        String json = userKv.decodeString(idType);
        list = GsonUtil.jsonToList(json, ImageFileBean.class);
        return list;
    }

    public void addSaveImageFile(String idType, String filePath) {
        if (userKv == null) return;
        List<ImageFileBean> list = getSaveImageFile(idType);
        list.add(new ImageFileBean(filePath));
        userKv.encode(idType, GsonUtil.BeanToJson(list));
    }

    public void deleteSaveImageFile(String idType, String filePath) {
        if (userKv == null) return;
        List<ImageFileBean> list = getSaveImageFile(idType);
        for (int i = 0; i < list.size(); i++) {
            if (TextUtils.equals(filePath, list.get(i).getPath())) {
                list.remove(i);
            }
        }
        userKv.encode(idType, GsonUtil.BeanToJson(list));
    }


    public void setSaveImageError(String ids) {
        List<String> list = getSaveImageError();
        list.add(ids);
        userKv.encode("saveList", GsonUtil.BeanToJson(list));
    }

    public List<String> getSaveImageError() {
        List<String> list = new ArrayList<>();
        String json = userKv.decodeString("saveList");
        if (!TextUtils.isEmpty(json)) {
            list = GsonUtil.jsonToList(json, String.class);

        }
        return list;
    }


    public void removeSaveImageError(String ids) {
        List<String> list = getSaveImageError();
        for (int i = 0; i < list.size(); i++) {
            if (TextUtils.equals(ids, list.get(i))) {
                list.remove(i);
            }
        }
        userKv.encode("saveList", GsonUtil.BeanToJson(list));
    }

    //存储要存储的该点位id
    public void saveUploadPoint(String pointId) {
        List<String> list = getUploadPoint();
        boolean isHave = false;
        for (int i = 0; i < list.size(); i++) {
            if (TextUtils.equals(list.get(i), pointId)) {
                isHave = true;
            }
        }
        if (!isHave) {
            list.add(pointId);
            if (catchKv == null) return;
            catchKv.encode("pointIds", GsonUtil.BeanToJson(list));
        }
    }

    //获取要上传的存储点位
    public List<String> getUploadPoint() {
        List<String> list = new ArrayList<>();
        String json = catchKv.decodeString("pointIds");
        if (!TextUtils.isEmpty(json)) {
            list = GsonUtil.jsonToList(json, String.class);
        }
        return list;
    }


    public void deletePoint(String point) {
        List<String> list = getUploadPoint();
        for (int i = 0; i < list.size(); i++) {
            if (TextUtils.equals(point, list.get(i))) {
                list.remove(i);
            }
        }
        catchKv.encode("pointIds", GsonUtil.BeanToJson(list));
    }


    public void addUploadImage(String listId, String point, ImageUploadBean bean, String des) {
        List<CaUploadImage> list = getUploadImage();
        boolean isHave = false;
        for (int i = 0; i < list.size(); i++) {
            if (TextUtils.equals(list.get(i).getPointId(), point)) {
                list.get(i).getImageList().add(bean);
                isHave = true;
            }
        }
        if (!isHave) {
            List<ImageUploadBean> list1 = new ArrayList<>();
            list1.add(bean);
            list.add(new CaUploadImage(listId, point, list1, des));
        }
        if (catchKv == null) return;
        catchKv.encode("UploadImage", GsonUtil.BeanToJson(list));
        saveUpImageList(listId, des, 1, 0);
        EventBus.getDefault().post(new UploadEventLoad());
    }


    public List<CaUploadImage> getUploadImage() {
        List<CaUploadImage> list = new ArrayList<>();
        String json = catchKv.decodeString("UploadImage");
        if (!TextUtils.isEmpty(json)) {
            list = GsonUtil.jsonToList(json, CaUploadImage.class);
        }
        return list;
    }


    public void setImageSuccess(String url, String point) {
        List<CaUploadImage> list = getUploadImage();
        for (int i = 0; i < list.size(); i++) {
            if (TextUtils.equals(point, list.get(i).getPointId())) {
                for (int h = 0; h < list.get(i).getImageList().size(); h++) {
                    if (TextUtils.equals(url, list.get(i).getImageList().get(h).getPath())) {
                        list.get(i).getImageList().remove(h);
                        saveUpImageList(list.get(i).getListId(), list.get(i).getDes(), -1, 0);
                    }
                }
            }
        }
        if (catchKv == null) return;
        catchKv.encode("UploadImage", GsonUtil.BeanToJson(list));
    }


//    public void addSubmitPointImage(String point, GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO pictureUrlsDTO, String pointCheckId) {
//        if (catchKv == null) return;
//        SubMitListBean subMitListBean = getSubmitPoint(point);
//        List<GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO> checkListDTOList = subMitListBean.getCheckList();
//        List<GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO> pictureUrlsDTOS = new ArrayList<>();
//        for (int i = 0; i < checkListDTOList.size(); i++) {
//            if (TextUtils.equals(checkListDTOList.get(i).getId(), pointCheckId)) {
//                pictureUrlsDTOS = checkListDTOList.get(i).getPictureUrls();
//            }
//        }
//        pictureUrlsDTOS.add(pictureUrlsDTO);
//        KLog.e(GsonUtil.BeanToJson(checkListDTOList));
//        catchKv.encode(point + "point", GsonUtil.BeanToJson(subMitListBean));
//    }

    public void addSubmitPoint(String point, String proId, String description, String json, String listId) {
        if (catchKv == null) return;
        KLog.e("------", point + "---" + proId);
        List<SubMitPointBean> subMitPointBeans = new ArrayList<>();
        subMitPointBeans = getSubmitPoint();
        boolean isHAve = false;
        for (int i = 0; i < subMitPointBeans.size(); i++) {
            if (TextUtils.equals(point, subMitPointBeans.get(i).getPointId()) && TextUtils.equals(proId, subMitPointBeans.get(i).getProjId())) {
                isHAve = true;
                subMitPointBeans.set(i, new SubMitPointBean(point, proId, description, json, listId));
            }
        }
        if (!isHAve) {
            subMitPointBeans.add(new SubMitPointBean(point, proId, description, json, listId));
        }
        KLog.e("22223333", subMitPointBeans.size());
        saveUpImageList(listId, description, 0, 1);
        catchKv.encode("SubmitPoint", GsonUtil.BeanToJson(subMitPointBeans));
    }

    public List<SubMitPointBean> getSubmitPoint() {
        String json = catchKv.decodeString("SubmitPoint");
        List<SubMitPointBean> subMitPointList = new ArrayList<>();
        if (!TextUtils.isEmpty(json)) {
            subMitPointList = GsonUtil.jsonToList(json, SubMitPointBean.class);
        }
        KLog.e("------" + subMitPointList.size());
        return subMitPointList;
    }

    public void removeSubmitPoint(String point, String proId,int position) {
        if (catchKv == null) return;
        KLog.e("------" + point + "---" + proId);
        List<SubMitPointBean> subMitPointBeans = new ArrayList<>();
        subMitPointBeans = getSubmitPoint();
        subMitPointBeans.remove(position);
        KLog.e("------" + subMitPointBeans.size());
        catchKv.encode("SubmitPoint", GsonUtil.BeanToJson(subMitPointBeans));
    }


    public void addOnLineNoGET_REPORT_STATUS(GETREPORTBean bean) {
        if (catchKv == null) return;
        List<GETREPORTBean> list = getOnLineNoGET_REPORT_STATUS();
        boolean isHave = false;
        for (int i = 0; i < list.size(); i++) {
            if (TextUtils.equals(bean.getAssetId(), list.get(i).getAssetId())) {
                list.set(i, bean);
                isHave = true;
            }
        }
        if (!isHave) {
            list.add(bean);
        }
        saveUpImageList(bean.getListId(), bean.getDes(), 0, 1);
        catchKv.encode("online", GsonUtil.BeanToJson(list));
    }

    public void removeGetReportStatus(GETREPORTBean bean) {
        List<GETREPORTBean> list = getOnLineNoGET_REPORT_STATUS();
        for (int i = 0; i < list.size(); i++) {
            if (TextUtils.equals(bean.getAssetId(), list.get(i).getAssetId())) {
                list.remove(i);
            }
        }
        saveUpImageList(bean.getListId(), bean.getDes(), 0, -1);
        catchKv.encode("online", GsonUtil.BeanToJson(list));
    }

    public List<GETREPORTBean> getOnLineNoGET_REPORT_STATUS() {
        List<GETREPORTBean> list = new ArrayList<>();
        String json = catchKv.decodeString("online");
        if (!TextUtils.isEmpty(json)) {
            list = GsonUtil.jsonToList(json, GETREPORTBean.class);
        }
        return list;
    }


    public void addStartPause(String id, String json, String des) {
        if (catchKv == null) return;
        List<StartPauseBean> list = getStartPause();
        list.add(new StartPauseBean(json, id));
        KLog.e(GsonUtil.BeanToJson(list));
        saveUpImageList(id, des, 0, 1);
        catchKv.encode("StartPause", GsonUtil.BeanToJson(list));
    }

    public void removeStartPause(int position) {
        List<StartPauseBean> list = getStartPause();
        list.remove(position);
        catchKv.encode("StartPause", GsonUtil.BeanToJson(list));
    }

    public List<StartPauseBean> getStartPause() {
        List<StartPauseBean> list = new ArrayList<>();
        String json = catchKv.decodeString("StartPause");
        if (!TextUtils.isEmpty(json)) {
            list = GsonUtil.jsonToList(json, StartPauseBean.class);
        }
        KLog.e(GsonUtil.BeanToJson(list));
        return list;
    }

/////////////////

    public void addFinish(String id, String json, String tId, String taskId, String remark, String time, String data, String des) {
        if (catchKv == null) return;
        List<StartPauseBean> list = getFinish();
        list.add(new StartPauseBean(id, json, tId, taskId, remark, time, data));
        saveUpImageList(json, des, 0, 1);
        catchKv.encode("Finish", GsonUtil.BeanToJson(list));
    }

    public void removeFinish(int position) {
        List<StartPauseBean> list = getFinish();
        StartPauseBean bean = list.get(position);
        list.remove(position);
        saveUpImageList(bean.getJson(), bean.getDes(), 0, -1);
        catchKv.encode("Finish", GsonUtil.BeanToJson(list));
    }

    public List<StartPauseBean> getFinish() {
        List<StartPauseBean> list = new ArrayList<>();
        String json = catchKv.decodeString("Finish");
        if (!TextUtils.isEmpty(json)) {
            list = GsonUtil.jsonToList(json, StartPauseBean.class);
        }
        return list;
    }


    public void clearCatch() {
        catchKv.clearAll();
    }


    public void addMapJson(String mapKey, String json) {
        if (userKv == null) return;
        userKv.encode(mapKey + "map_json", json);
    }

    public String getMapJson(String mapKey) {
        List<StartPauseBean> list = new ArrayList<>();
        String json = userKv.decodeString(mapKey + "map_json");
        return json;
    }


    public void putPointScanMarkers(String key) {
        userKv.encode("point_" + key, true);
    }

    public Boolean getPointScanMarkers(String key) {
        return userKv.decodeBool("point_" + key, false);
    }

//    public void putPointNFCScanMarkers(String key){
//        catchKv.encode("point_nfc_"+key,true);
//    }
//
//    public Boolean getPointNFCScanMarkers(String key){
//        return catchKv.decodeBool("point_nfc_"+key,false);
//    }

    public void addNoNetImage(List<GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO> list) {
        List<GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO> nenList = getNoNetImage();
        if (catchKv == null) return;
        nenList.addAll(list);
        catchKv.encode("getNoNetImage", GsonUtil.BeanToJson(nenList));
    }


    public List<GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO> getNoNetImage() {
        List<GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO> list = new ArrayList<>();
        String json = catchKv.decodeString("getNoNetImage");
        if (!TextUtils.isEmpty(json)) {
            list = GsonUtil.jsonToList(json, GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO.class);
        }
        return list;
    }

    public void saveJumpPoint(String listId, String json, String proId) {
        if (catchKv == null) return;
        List<StartPauseBean> list = getJumpPoint();
        StartPauseBean bean = new StartPauseBean(json, listId);
        bean.setPorId(proId);
        list.add(bean);
        catchKv.encode("saveJumpPoint", GsonUtil.BeanToJson(list));
    }

    public List<StartPauseBean> getJumpPoint() {
        List<StartPauseBean> list = new ArrayList<>();
        String json = catchKv.decodeString("saveJumpPoint");
        if (!TextUtils.isEmpty(json)) {
            list = GsonUtil.jsonToList(json, StartPauseBean.class);
        }
        return list;
    }


    public void removeJumpPoint(int position) {
        List<StartPauseBean> list = getJumpPoint();
        list.remove(position);
    }


    public void saveUpImageList(String listId, String des, int fileNum, int num) {
        Map<String, UploadImageBean> map = getUpImageList();
        if (map.containsKey(listId)) {
            UploadImageBean bean = map.get(listId);
            bean.setFileTotalCount(bean.getFileTotalCount() + fileNum);
            bean.setFileSurplusCount(bean.getFileTotalCount());
            bean.setSurplusCount(bean.getFileTotalCount() + num);
            bean.setTotalCount(bean.getSurplusCount() + bean.getFileTotalCount());
            bean.setOwnerId(listId);
            bean.setDesc(des);
            map.put(listId, bean);
        } else {
            UploadImageBean bean = new UploadImageBean();
            bean.setFileTotalCount(fileNum);
            bean.setFileSurplusCount(fileNum);
            bean.setSurplusCount(num);
            bean.setDesc(des);
            bean.setOwnerId(listId);
            bean.setTotalCount(fileNum + num);
            map.put(listId, bean);
        }
        KLog.e(GsonUtil.BeanToJson(map));
        catchKv.encode("getUpImageBean", GsonUtil.BeanToJson(map));
    }


    public Map<String, UploadImageBean> getUpImageList() {
        String json = catchKv.decodeString("getUpImageBean");
        KLog.e(json);
        Map<String, UploadImageBean> map = new HashMap<>();
        if (!TextUtils.isEmpty(json)) {
            map = GsonUtil.jsonToGenericMap(json, UploadImageBean.class);
            Iterator<Map.Entry<String, UploadImageBean>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, UploadImageBean> entry = iterator.next();
                UploadImageBean bean = entry.getValue();
                if (bean.getSurplusCount() <= 0 && bean.getFileTotalCount() <= 0 && bean.getFileSurplusCount() <= 0) {
                    iterator.remove();
                }
            }
        }
        boolean isHave = false;
        List<CaUploadImage> pointImage = CacheHelper.getInstance().getUploadImage();
        for (CaUploadImage bean : pointImage) {
            for (int i = 0; i < bean.getImageList().size(); i++) {
                isHave = true;
            }
        }


        List<StartPauseBean> inspectStateList = CacheHelper.getInstance().getStartPause();


        List<GETREPORTBean> list = CacheHelper.getInstance().getOnLineNoGET_REPORT_STATUS();
        List<SubMitPointBean> subMitListBean = CacheHelper.getInstance().getSubmitPoint();
        List<StartPauseBean> listFinish = CacheHelper.getInstance().getFinish();
        if(Utils.isEmpty(inspectStateList)&!isHave&Utils.isEmpty(list)&Utils.isEmpty(subMitListBean)&Utils.isEmpty(list)&Utils.isEmpty(listFinish)){
            map.clear();
        }
        catchKv.encode("getUpImageBean", GsonUtil.BeanToJson(map));
        return map;
    }


}
